import { View } from '@tarojs/components';

import { TComponent } from '@material/typeing';
import { FC, useCallback, useEffect, useRef, useState } from 'react';
import KImage from '../image';
import Toast from '../toast';
import KTextarea from '../textarea';
import { pxTransform } from '../../utils';
import { clsx } from 'react-runtime-clsx';
import { clearFrameTimeout, frameTimeout } from '@material/helpers';
import { useWatchNetwork } from '@material/hooks';
import $style from './index.scss';

export interface ChatInputProps extends TComponent {
    onKeybordChange?: (value: number) => void;
    onFocus?: () => void;
    onBlur?: () => void;
    onSend?: (value: string) => void;
    disabled?: boolean;
}
const KChatInput: FC<ChatInputProps> = function (props) {
    const { onKeybordChange, onFocus, onBlur, disabled, onSend } = props;
    const postionRef = useRef({ top: 0, bottom: 0 });
    const [inputValue, setInputValue] = useState('');
    const [inputFocus, setInputFocus] = useState(false);
    const isButtonTouched = useRef(false);
    const isHasNetWork = useWatchNetwork();
    const timerRef = useRef(0);

    const handleButtonTouchStart = useCallback(() => {
        isButtonTouched.current = true;
    }, []);

    const focusHandle = (e: Event, element: HTMLTextAreaElement | null) => {
        const textareaElement = (element || e.target) as HTMLTextAreaElement;
        const { top, bottom } = textareaElement.getBoundingClientRect();
        postionRef.current = {
            top,
            bottom
        };
        setInputFocus(true);
        timerRef.current = frameTimeout(() => {
            const rect = textareaElement.getBoundingClientRect();
            if (
                postionRef.current.top - rect.top < 100 &&
                postionRef.current.bottom - rect.bottom < 100
            ) {
                onKeybordChange && onKeybordChange(300);
            } else {
                clearFrameTimeout(timerRef.current);
            }
            postionRef.current = {
                top: 0,
                bottom: 0
            };
        }, 1000);
        onFocus && onFocus();
    };

    const sendHandle = function () {
        if (disabled) {
            Toast({
                content: '智能助手回复中，请稍候',
                duration: 3
            });
            return;
        }
        if (!inputValue.trim()) {
            Toast({
                content: '输入内容不能为空',
                duration: 3
            });
            return;
        }
        if (!isHasNetWork) {
            Toast({
                content: '网络异常，请稍后重试！',
                duration: 3
            });
            return;
        }
        onSend && onSend(inputValue);
        setInputValue('');
        setInputFocus(false);
    };

    useEffect(() => {
        if (!inputFocus) {
            onKeybordChange && onKeybordChange(0);
            clearFrameTimeout(timerRef.current);
            postionRef.current = {
                top: 0,
                bottom: 0
            };
            onBlur && onBlur();
        }
    }, [inputFocus, onBlur, onKeybordChange]);

    const blurHandle = () => {
        if (!isButtonTouched.current) {
            setInputFocus(false);
        }
        // 重置标记（在下一次事件循环前）
        isButtonTouched.current = false;
    };
    const isShowButton = inputFocus || inputValue;

    return (
        <View className={clsx($style['chat-input'])}>
            <View className={clsx($style.inner)}>
                <KTextarea
                    className={$style.textarea}
                    value={inputValue}
                    placeholder='请输入你想咨询的问题'
                    maxLength={200}
                    autoSize={true}
                    onChange={(value) => setInputValue(value)}
                    onBlur={blurHandle}
                    onFocus={focusHandle}
                ></KTextarea>
                <div
                    className={clsx([
                        $style.button,
                        isShowButton ? $style['button-show'] : $style['button-hidden'],
                        { [$style['button-disabled']]: disabled }
                    ])}
                    onTouchStart={handleButtonTouchStart}
                    onTouchEnd={sendHandle}
                    onClick={(e) => e.preventDefault()}
                >
                    <div className={$style['button-wrap']}>
                        <KImage
                            size={pxTransform(36)}
                            src='https://kf-ui.cdn-go.cn/weapp-image/latest/weapp-110/image/ai/input_icon_send.png'
                        ></KImage>
                    </div>
                </div>
            </View>
            <View
                className={clsx($style.warning)}
                style={{ display: inputFocus ? 'none' : 'flex' }}
            >
                内容由AI生成
            </View>
        </View>
    );
};
KChatInput.displayName = 'KChatInput';
export default KChatInput;
